<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/8
 * Time: 9:35
 */

namespace common\business\position;


use common\business\DbHandler;
use common\models\Department;
use common\models\Position;
use common\result\ActionResult;

class PositionApiHandler extends DbHandler
{
    /**
     * @param $obj Position
     * @return ActionResult
     */
    public function createPosition($obj){
        $this->updateParentPositionAndDepartment($obj);
        return $this->create($obj);
    }


    /**
     * @param $obj Position
     */
    protected function updateParentPositionAndDepartment($obj){
        $parentPositionInDb = Position::findOne([
            'number' => $obj->parent_number
        ]);
        if ($parentPositionInDb){
            $obj->parent_id = $parentPositionInDb->id;
        }
        $departmentInDb = Department::findOne([
            'number' => $obj->department_number
        ]);
        if($departmentInDb){
            $obj->department_id = $departmentInDb->id;
        }
    }

    /**
     * @param Position $newObj
     * @param Position $oldObj
     * @return ActionResult
     */
    public function updatePosition($newObj, $oldObj = null){
        $this->updateParentPositionAndDepartment($newObj);
        if (!$oldObj){
            $oldObj = Position::findOne([
                'number' => $newObj->number,
            ]);
        }
        return $this->update($newObj, $oldObj, [
            'name',
            'number',
            'parent_id',
            'parent_number',
            'parent_name',
            'domain',
            'department_id',
            'department_number',
            'department_name',
            'department_display_name',
            'kd_id',
            'parent_kd_id',
            'department_kd_id',
        ]);
    }
}